package com.dbh.jdk.concurrent;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 *  保存堆栈信息的线程池示例
 *
 * @author dongbanghui
 * @date 2018/06/02
 */
public class TraceThreadPoolExector extends ThreadPoolExecutor {

    public TraceThreadPoolExector(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    }

    @Override
    public void execute(Runnable task) {
        super.execute(wrap(task, clientTrance(), Thread.currentThread().getName()));
    }

    private Exception clientTrance(){
        return new Exception("Client stack trace");
    }

    private Runnable wrap(final Runnable task, final Exception clientStatck, String clientThreadName){
        return () -> {
            try {
                task.run();
            } catch (Exception e) {
                clientStatck.printStackTrace();
                throw e;
            }
        };
    }
}
